#! /bin/sh


#_api_key
_api_key="cd5a3a29a9eed4a3006665846e58e074"

#是否上传远端
needUpload="on"

#构建类型
buildType=""

#构建输出目录
outputs=build/app/outputs/flutter-apk/

#文件名
filename="app-debug.apk"

#更新日志
buildUpdateDescription="""
1. 适配flutter-3.10.0版本.
2. 优化webview页面.
3. 优化代码.
"""

helper() {
    echo "请输入参数"
    echo "-d 构建debug版本"
    echo "-r 构建release版本"
    echo "-u on/off 上传开关"
}
getFileName() {
    if [ $buildType == "debug" ]; then
        filename="app-debug.apk"
    else
        filename="app-release.apk"
    fi
}


#上传方法
uploadFir() {
    echo "准备上传"
    echo "切换到输出目录$outputs"
    cd $outputs
    # 上传到APP管理平台
    curl  -X POST --url https://www.pgyer.com/apiv2/app/upload -F "file=@$filename" -F "_api_key=$_api_key" -F "buildUpdateDescription=$buildUpdateDescription" > result.json
    echo "返回的json数据如下:"
    cat result.json | jq .
    echo "二维码下载地址如下:"
    cat result.json | jq '.data.buildQRCodeURL'
    exit
}

#清除临时文件
clearTemp() {
    removeFile temp.txt
    removeFile result.json
    removeFile appinfo.txt
}

#删除文件
removeFile() {
    filename=$1
    if [[ -e $filename ]]; then
        rm -f $filename
    fi
}

if [ $# -eq 0 ]; then
    helper
    exit
fi

#获取命令参数
while getopts :dru: opt; do
    case $opt in
    d)
        buildType="debug"
        ;;
    r)
        buildType="release"
        ;;
    u)
        needUpload="$OPTARG"
        ;;
    :)
        echo "$opt"
        echo "请输入参数 on/off"
        exit 1
        ;;
    ?)
        helper
        exit 2
        ;;
    esac
done

#执行顺序
clearTemp
echo "构建模式:$buildType"
echo "是否上传:$needUpload"
flutter build apk --$buildType
if [ $? -eq 0 ]; then
    echo "构建成功"
    if [ $needUpload == "on" ]; then
        getFileName
        uploadFir
    fi
    clearTemp
else
    echo "构建失败"
fi
exit
